package org.example.springblog.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.springblog.constants.Constants;
import org.example.springblog.model.Result;
import org.example.springblog.model.UserInfo;
import org.example.springblog.service.UserService;
import org.example.springblog.utils.JwtUtils;
import org.example.springblog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/8/3
 * Time: 20:00
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result<Object> login(String userName, String password){
        log.info("/user/login接收参数: userName:{}, password:{}", userName, password);
        //1.参数校验合法性
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            log.error("账号和密码不能为空");
            return Result.fail("账号和密码不能为空");
        }
        //2.从数据库中查找用户
        UserInfo userInfo = userService.selectByUserName(userName);
        if (userInfo == null){
            log.error("用户不存在");
            return Result.fail("用户不存在");
        }
        //3.校验密码是否正确
        if (!SecurityUtils.verify(password, userInfo.getPassword())){
            log.error("密码错误");
            return Result.fail("密码错误");
        }
        //4.密码正确,返回token
        Map<String,Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID,userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME,userInfo.getUserName());
        String token = JwtUtils.generateToken(claim);
        log.info("token:{}",token);
        return Result.success(token);
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Result<String> register(String userName,String password,String githubUrl){
        log.info("/user/register接收参数: userName:{}, password:{},githubUrl{}", userName, password,githubUrl);
        //1.参数校验合法性
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            log.error("账号和密码不能为空");
            return Result.fail("账号和密码不能为空");
        }
        //处理密码
        String encryptPassword = SecurityUtils.encrypt(password);
        try {
            Integer ret = userService.register(userName, encryptPassword, githubUrl);
            if (ret == 1) {
                return Result.success("注册成功");
            }
        }catch (Exception e){
            log.error("该用户名已存在");
        }
        return Result.fail("该用户名已存在");
    }

    @RequestMapping(value = "/modify",method = RequestMethod.POST)
    public Result<String> modify(Integer id,String userName,String password,String githubUrl){
        log.info("/user/modify接收参数: userName:{}, password:{},githubUrl{}", userName, password,githubUrl);
        //1.参数校验合法性
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            log.error("账号和密码不能为空");
            return Result.fail("账号和密码不能为空");
        }
        //处理密码
        String encryptPassword = SecurityUtils.encrypt(password);
        try {
            Integer ret = userService.modify(id,userName, encryptPassword, githubUrl);
            if (ret == 1) {
                return Result.success("修改成功");
            }
        }catch (Exception e){
            log.error("该用户名已存在");
        }
        return Result.fail("该用户名已存在");
    }

    @RequestMapping("/getLoginUserInfo")
    public UserInfo getLoginUserInfo(HttpServletRequest request){
        //获取token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        //从token中获取用户id
        Integer userId = JwtUtils.getIdByToken(token);
        if (userId == null){
            return null;
        }
        return userService.getLoginUserInfo(userId);
    }

    @RequestMapping("/getAuthorUserInfo")
    public UserInfo getAuthorUserInfo(Integer blogId){
        //根据博客id获取用户id,再获取用户信息
        return userService.getAuthorUserInfo(blogId);
    }

    @RequestMapping("/getUserList")
    public List<UserInfo> getUserList(){
        return userService.getUserList();
    }
}
